<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: kane <chengjin005@163.com> 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\FreightModel;
use app\admin\model\FreightTplModel;
use cmf\controller\AdminBaseController;
use app\admin\model\GoodCategoryModel;
use app\admin\model\GoodsModel;
use think\Db;
use app\admin\model\RouteModel;
use app\admin\model\ThemeModel;

/**
 * Class StockController
 * @package app\admin\controller
 * @adminMenuRoot(
 *     'name'   => '平台管理',
 *     'action' => 'default',
 *     'parent' => '',
 *     'display'=> true,
 *     'order'  => 10000,
 *     'icon'   => 'home',
 *     'remark' => '平台管理'
 * )
 */
class StockController extends AdminBaseController
{
    /**
     * 商品管理
     * @adminMenu(
     *     'name'   => '商品管理',
     *     'parent' => 'admin/Stock/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 30,
     *     'icon'   => '',
     *     'remark' => '商品管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $param = $this->request->param();

        $categoryId = $this->request->param('category', 0, 'intval');

        $goodsmodel = new GoodsModel();
        $data        = $goodsmodel->adminGoodsList($param);

        $data->appends($param);


        $goodCategoryModel = new GoodCategoryModel();
        $categoryTree        = $goodCategoryModel->adminCategoryTree($categoryId);

        $this->assign('start_time', isset($param['start_time']) ? $param['start_time'] : '');
        $this->assign('end_time', isset($param['end_time']) ? $param['end_time'] : '');
        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('articles', $data->items());
        $this->assign('category_tree', $categoryTree);
        $this->assign('category', $categoryId);
        $this->assign('page', $data->render());


        return $this->fetch();
    }
    /**
     * 添加商品
     * @adminMenu(
     *     'name'   => '添加商品',
     *     'parent' => 'admin/Stock/index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 30,
     *     'icon'   => '',
     *     'remark' => '添加商品',
     *     'param'  => ''
     * )
     */
    public function add_good()
    {
        if(!input('post.')){
            $themeModel        = new ThemeModel();
            $freight = new FreightTplModel();
            $fright_list=$freight->get_freight_tpl();
            $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');
            $this->assign('article_theme_files', $articleThemeFiles);
            $this->assign('fright_list', $fright_list);
            return $this->fetch();
        }else{
            $data   = $this->request->param();

            //状态只能设置默认值。未发布、未置顶、未推荐
            $data['post']['post_status'] = 0;
            $data['post']['is_top'] = 0;
            $data['post']['recommended'] = 0;

            $post   = $data['post'];

            $result = $this->validate($post, 'Goods');
            if ($result !== true) {
                $this->error($result);
            }
            if($post['shipping_fee_type']==4&&$post['shipping_fee']==null){
                $this->error('运费不能为空');
            }
            if($post['shipping_fee_type']==1&&$post['goods_weight']==null){
                $this->error(' 重量不能为空');
            }
            if($post['shipping_fee_type']==2&&$post['goods_volume']==null){
                $this->error('体积不能为空');
            }
            if($post['shipping_tpl']==0||$post['shipping_tpl']==null){
                $this->error('请选择运费模版');
            }
            $GoodsModel = new GoodsModel();

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }else{
                $this->error('商品相册不能为空!');
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }



            $GoodsModel->adminAddGood($data['post'], $data['post']['categories']);

            $data['post']['id'] = $GoodsModel->id;
            $hookParam          = [
                'is_add'  => true,
                'article' => $data['post']
            ];
            hook('portal_admin_after_save_article', $hookParam);


            $this->success('添加成功!', url('Stock/edit_good', ['id' => $GoodsModel->id]));
        }

    }
    /**
     * 编辑商品
     * @adminMenu(
     *     'name'   => '编辑商品',
     *     'parent' => 'admin/Stock/index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 30,
     *     'icon'   => '',
     *     'remark' => '编辑商品',
     *     'param'  => ''
     * )
     */
    public function edit_good()
    {
        if(!input('post.')){
            $id = $this->request->param('id', 0, 'intval');
            $GoodsModel = new GoodsModel();
            $post            = $GoodsModel->where('id', $id)->find();
            $postCategories  = $post->categories()->alias('a')->column('a.name', 'a.id');
            $postCategoryIds = implode(',', array_keys($postCategories));

            $themeModel        = new ThemeModel();
            $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');
            $freight = new FreightTplModel();
            $fright_list=$freight->get_freight_tpl();
            $this->assign('fright_list', $fright_list);
            $this->assign('article_theme_files', $articleThemeFiles);
            $this->assign('post', $post);
            $this->assign('post_categories', $postCategories);
            $this->assign('post_category_ids', $postCategoryIds);
            return $this->fetch();
        }else{
            $data   = $this->request->param();

            //需要抹除发布、置顶、推荐的修改。
//            unset($data['post']['post_status']);
//            unset($data['post']['is_top']);
//            unset($data['post']['recommended']);

            $post   = $data['post'];

            $result = $this->validate($post, 'Goods');

            if ($result !== true) {
                $this->error($result);
            }
            if($post['shipping_fee_type']==4&&$post['shipping_fee']==null){
                $this->error('运费不能为空');
            }
            if($post['shipping_fee_type']==1&&$post['goods_weight']==null){
                $this->error(' 重量不能为空');
            }
            if($post['shipping_fee_type']==2&&$post['goods_volume']==null){
                $this->error('体积不能为空');
            }
            if($post['shipping_tpl']==0||$post['shipping_tpl']==null){
                $this->error('请选择运费模版');
            }
            $GoodsModel = new GoodsModel();

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }else{
                $this->error('商品相册不能为空!');
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }

            $GoodsModel->adminEditGoods($data['post'], $data['post']['categories']);

            $hookParam = [
                'is_add'  => false,
                'article' => $data['post']
            ];
            hook('portal_admin_after_save_article', $hookParam);

           $this->success('保存成功!');
        }

    }

    /**
     * 商品分类
     * @adminMenu(
     *     'name'   => '商品分类',
     *     'parent' => 'admin/Stock/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 30,
     *     'icon'   => '',
     *     'remark' => '商品分类',
     *     'param'  => ''
     * )
     */
    public function category_index()
    {
        $goodCategoryModel = new GoodCategoryModel();
        $categoryTree        = $goodCategoryModel->adminCategoryTableTree();
        $this->assign('category_tree', $categoryTree);
        return $this->fetch();
    }

    /**
     * 添加商品分类
     * @adminMenu(
     *     'name'   => '添加商品分类',
     *     'parent' => 'admin/Stock/category_index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 30,
     *     'icon'   => '',
     *     'remark' => '添加商品分类',
     *     'param'  => ''
     * )
     */
    public function add_category()
    {
        $goodCategoryModel = new GoodCategoryModel();
        if(!input('post.')){
            $parentId            = $this->request->param('parent', 0, 'intval');

            $categoriesTree      = $goodCategoryModel->adminCategoryTree($parentId);

            $themeModel        = new ThemeModel();
            $listThemeFiles    = $themeModel->getActionThemeFiles('portal/List/index');
            $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');

            $this->assign('list_theme_files', $listThemeFiles);
            $this->assign('article_theme_files', $articleThemeFiles);
            $this->assign('categories_tree', $categoriesTree);
            return $this->fetch();
        }else{
            $data = $this->request->param();
            $result = $this->validate($data, 'GoodCategory');
            if ($result !== true) {
                $this->error($result);
            }
            $result = $goodCategoryModel->addCategory($data);
            if ($result === false) {
                $this->error('添加失败!');
            }
            $this->success('添加成功!', url('Stock/category_index'));
        }
    }
    /**
     * 编辑商品分类
     * @adminMenu(
     *     'name'   => '编辑商品分类',
     *     'parent' => 'admin/Stock/category_index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 30,
     *     'icon'   => '',
     *     'remark' => '编辑商品分类',
     *     'param'  => ''
     * )
     */
    public function edit_category()
    {
        $goodCategoryModel = new GoodCategoryModel();
        if(!input('post.')){
            $id = $this->request->param('id', 0, 'intval');
            if ($id > 0) {
                $category = GoodCategoryModel::get($id)->toArray();


                $categoriesTree      = $goodCategoryModel->adminCategoryTree($category['parent_id'], $id);

                $themeModel        = new ThemeModel();
                $listThemeFiles    = $themeModel->getActionThemeFiles('portal/List/index');
                $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');

                $routeModel = new RouteModel();
                $alias      = $routeModel->getUrl('portal/Category/index', ['id' => $id]);

                $category['alias'] = $alias;
                $this->assign($category);
                $this->assign('list_theme_files', $listThemeFiles);
                $this->assign('article_theme_files', $articleThemeFiles);
                $this->assign('categories_tree', $categoriesTree);
                return $this->fetch();
            } else {
                $this->error('操作错误!');
            }
        }else{
            $data = $this->request->param();

            $result = $this->validate($data, 'GoodCategory');

            if ($result !== true) {
                $this->error($result);
            }

            $result = $goodCategoryModel->editCategory($data);

            if ($result === false) {
                $this->error('保存失败!');
            }

            $this->success('保存成功!');
        }
    }
    /**
     * 删除商品分类
     * @adminMenu(
     *     'name'   => '删除商品分类',
     *     'parent' => 'admin/Stock/category_index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 30,
     *     'icon'   => '',
     *     'remark' => '删除商品分类',
     *     'param'  => ''
     * )
     */
    public function del_category()
    {
        $goodCategoryModel = new GoodCategoryModel();
        $id                  = $this->request->param('id');
        //获取删除的内容
        $findCategory = $goodCategoryModel->where('id', $id)->find();

        if (empty($findCategory)) {
            $this->error('分类不存在!');
        }
//判断此分类有无子分类（不算被删除的子分类）
        $categoryChildrenCount = $goodCategoryModel->where(['parent_id' => $id,'delete_time' => 0])->count();

        if ($categoryChildrenCount > 0) {
            $this->error('此分类有子类无法删除!');
        }

        $categoryPostCount = Db::name('portal_category_post')->where('category_id', $id)->count();

        if ($categoryPostCount > 0) {
            $this->error('此分类有文章无法删除!');
        }

        $data   = [
            'object_id'   => $findCategory['id'],
            'create_time' => time(),
            'table_name'  => 'good_category',
            'name'        => $findCategory['name'],
            'user_id'        => cmf_get_current_admin_id(),
        ];
        $result = $goodCategoryModel
            ->where('id', $id)
            ->update(['delete_time' => time()]);
        if ($result) {
            Db::name('recycleBin')->insert($data);
            $this->success('删除成功!');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 商品分类排序
     * @adminMenu(
     *     'name'   => '商品分类排序',
     *     'parent' => 'admin/Stock/category_index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 30,
     *     'icon'   => '',
     *     'remark' => '商品分类排序',
     *     'param'  => ''
     * )
     */
    public function category_listOrder()
    {
        parent::listOrders(Db::name('good_category'));
        $this->success("排序更新成功！", '');
    }
    /**
     * 商品分类选择对话框
     * @adminMenu(
     *     'name'   => '商品分类选择对话框',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '商品分类选择对话框',
     *     'param'  => ''
     * )
     */
    public function select()
    {
        $ids                 = $this->request->param('ids');
        $selectedIds         = explode(',', $ids);

        $goodCategoryModel = new GoodCategoryModel();

        $tpl = <<<tpl
<tr class='data-item-tr'>
    <td>
        <input type='checkbox' class='js-check' data-yid='js-check-y' data-xid='js-check-x' name='ids[]'
               value='\$id' data-name='\$name' \$checked>
    </td>
    <td>\$id</td>
    <td>\$spacer <a href='\$url' target='_blank'>\$name</a></td>
</tr>
tpl;

        $categoryTree = $goodCategoryModel->adminCategoryTableTree($selectedIds, $tpl);

        $where      = ['delete_time' => 0];
        $categories = $goodCategoryModel->where($where)->select();

        $this->assign('categories', $categories);
        $this->assign('selectedIds', $selectedIds);
        $this->assign('categories_tree', $categoryTree);
        return $this->fetch();
    }

    /**
     * 商品删除
     * @adminMenu(
     *     'name'   => '商品删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '商品删除',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $param           = $this->request->param();
        $GoodsModel = new GoodsModel();

        if (isset($param['id'])) {
            $id           = $this->request->param('id', 0, 'intval');
            $result       = $GoodsModel->where(['id' => $id])->find();
            $data         = [
                'object_id'   => $result['id'],
                'create_time' => time(),
                'table_name'  => 'goods',
                'name'        => $result['post_title'],
                'user_id'=>cmf_get_current_admin_id()
            ];
            $resultPortal = $GoodsModel
                ->where(['id' => $id])
                ->update(['delete_time' => time()]);
            if ($resultPortal) {
                Db::name('good_category_goods')->where(['goods_id'=>$id])->update(['status'=>0]);
                Db::name('recycleBin')->insert($data);
            }
            $this->success("删除成功！", '');

        }

        if (isset($param['ids'])) {
            $ids     = $this->request->param('ids/a');
            $recycle = $GoodsModel->where(['id' => ['in', $ids]])->select();
            $result  = $GoodsModel->where(['id' => ['in', $ids]])->update(['delete_time' => time()]);
            if ($result) {
                Db::name('good_category_goods')->where(['post_id' => ['in', $ids]])->update(['status'=>0]);
                foreach ($recycle as $value) {
                    $data = [
                        'object_id'   => $value['id'],
                        'create_time' => time(),
                        'table_name'  => 'goods',
                        'name'        => $value['post_title'],
                        'user_id'=>cmf_get_current_admin_id()
                    ];
                    Db::name('recycleBin')->insert($data);
                }
                $this->success("删除成功！", '');
            }
        }
    }

    /**
     * 商品发布
     * @adminMenu(
     *     'name'   => '商品发布',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '商品发布',
     *     'param'  => ''
     * )
     */
    public function publish()
    {
        $param           = $this->request->param();
        $GoodsModel = new GoodsModel();
        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');

            $GoodsModel->where(['id' => ['in', $ids]])->update(['post_status' => 1, 'published_time' => time()]);

            $this->success("发布成功！", '');
        }

        if (isset($param['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');

            $GoodsModel->where(['id' => ['in', $ids]])->update(['post_status' => 0]);

            $this->success("取消发布成功！", '');
        }

    }

    /**
     * 商品置顶
     * @adminMenu(
     *     'name'   => '商品置顶',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '商品置顶',
     *     'param'  => ''
     * )
     */
    public function top()
    {
        $param           = $this->request->param();
        $GoodsModel = new GoodsModel();

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');
            $GoodsModel->where(['id' => ['in', $ids]])->update(['is_top' => 1]);
            $this->success("置顶成功！", '');

        }

        if (isset($_POST['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');
            $GoodsModel->where(['id' => ['in', $ids]])->update(['is_top' => 0]);

            $this->success("取消置顶成功！", '');
        }
    }

    /**
     * 商品推荐
     * @adminMenu(
     *     'name'   => '商品推荐',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '商品推荐',
     *     'param'  => ''
     * )
     */
    public function recommend()
    {
        $param           = $this->request->param();
        $GoodsModel = new GoodsModel();

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');
            $GoodsModel->where(['id' => ['in', $ids]])->update(['recommended' => 1]);
            $this->success("推荐成功！", '');

        }
        if (isset($param['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');
            $GoodsModel->where(['id' => ['in', $ids]])->update(['recommended' => 0]);
            $this->success("取消推荐成功！", '');

        }
    }

    /**
     * 商品排序
     * @adminMenu(
     *     'name'   => '商品排序',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '商品排序',
     *     'param'  => ''
     * )
     */
    public function listOrder()
    {
        parent::listOrders(Db::name('good_category_goods'));
        $this->success("排序更新成功！", '');
    }




}